package com.streamer.app.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.streamer.app.R
import com.streamer.app.adapter.UserListAdapter
import com.streamer.app.model.User
import android.widget.EditText
import android.widget.ImageView
import android.widget.SeekBar
import android.view.ViewGroup
import android.content.ContentResolver
import android.database.Cursor
import android.provider.OpenableColumns
import android.net.Uri
import android.util.Log
import com.streamer.app.ThreePaneLiveActivity
import com.streamer.app.adapter.LocalPlayAdapter
import com.streamer.app.adapter.NetWorkPlayAdapter
import com.streamer.app.bean.Item
import org.json.JSONArray
import org.json.JSONObject


object BottomSheetUtils {
    // Keep reference to the currently shown Local Play dialog for UI updates
    @SuppressLint("StaticFieldLeak")
    private var lastLocalPlayDialog: BottomSheetDialog? = null
    
    // Keep reference to the currently shown Muted List dialog to prevent duplicate display
    @SuppressLint("StaticFieldLeak")
    private var currentMutedListDialog: BottomSheetDialog? = null
    
    // Keep reference to the currently shown Kicked List dialog to prevent duplicate display
    @SuppressLint("StaticFieldLeak")
    private var currentKickedListDialog: BottomSheetDialog? = null

    /**
     * 显示禁言名单底部弹窗
     */
    fun showMutedListDialog(
        context: Context,
        mutedUsers: List<User>,
        onUnmuteUser: ((User) -> Unit)? = null,
        onUnmuteAll: (() -> Unit)? = null
    ) {
        // 如果已经有禁言名单弹窗在显示，则不重复显示
        if (currentMutedListDialog != null && currentMutedListDialog!!.isShowing) {
            return
        }
        
        showUserListBottomSheet(
            context = context,
            title = "禁言名单(${mutedUsers.size})",
            users = mutedUsers,
            actionText = "解除禁言",
            globalActionText = "全部解禁",
            onUserAction = { user, action ->
                if (action == "unmute") {
                    onUnmuteUser?.invoke(user)
                }
            },
            onGlobalAction = onUnmuteAll,
            dialogType = "muted_list"
        )
    }

    /**
     * 显示踢出房间名单底部弹窗
     */
    fun showKickedListDialog(
        context: Context,
        kickedUsers: List<User>,
        onUnmuteUser: ((User) -> Unit)? = null,
        onUnmuteAll: (() -> Unit)? = null
    ) {
        // 如果已经有踢出房间名单弹窗在显示，则不重复显示
        if (currentKickedListDialog != null && currentKickedListDialog!!.isShowing) {
            return
        }
        
        showUserListBottomSheet(
            context = context,
            title = "踢出房间名单(${kickedUsers.size})",
            users = kickedUsers,
            actionText = "解除禁言",
            globalActionText = "全部解禁",
            onUserAction = { user, action ->
                if (action == "unmute") {
                    onUnmuteUser?.invoke(user)
                }
            },
            onGlobalAction = onUnmuteAll,
            dialogType = "kicked_list"
        )
    }

    /**
     * 通用用户列表底部弹窗
     */
    private fun showUserListBottomSheet(
        context: Context,
        title: String,
        users: List<User>,
        actionText: String,
        globalActionText: String,
        onUserAction: ((User, String) -> Unit)? = null,
        onGlobalAction: (() -> Unit)? = null,
        dialogType: String? = null
    ) {
        val dialog = BottomSheetDialog(context)
        val dialogView =
            LayoutInflater.from(context).inflate(R.layout.bottom_sheet_user_list_simple, null)
        dialog.setContentView(dialogView)

        // 根据对话框类型保存引用
        when (dialogType) {
            "muted_list" -> currentMutedListDialog = dialog
            "kicked_list" -> currentKickedListDialog = dialog
        }

        // 设置弹窗属性
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)

        // 设置标题
        dialogView.findViewById<TextView>(R.id.tv_bottom_sheet_title).text = title

        // 设置RecyclerView
        val recyclerView = dialogView.findViewById<RecyclerView>(R.id.rv_user_list_simple)
        recyclerView.layoutManager = LinearLayoutManager(context)

        // 创建适配器
        val adapter = UserListAdapter(
            users = users.toMutableList(), onUserAction = { user, action ->
                onUserAction?.invoke(user, action)
            }, isMutedList = title.contains("禁言名单") || title.contains("踢出房间名单"),title
        )
        recyclerView.adapter = adapter

        // 设置全局操作按钮
        val globalActionButton = dialogView.findViewById<TextView>(R.id.btn_global_action)
        globalActionButton.text = globalActionText
        globalActionButton.setOnClickListener {
            onGlobalAction?.invoke()
            dialog.dismiss()
        }

        // 关闭按钮
        dialogView.findViewById<View>(R.id.iv_close_bottom_sheet).setOnClickListener {
            dialog.dismiss()
        }

        // 设置点击外部关闭和对话框关闭时的清理
        dialog.setOnCancelListener {
            // 清理对话框引用
            when (dialogType) {
                "muted_list" -> currentMutedListDialog = null
                "kicked_list" -> currentKickedListDialog = null
            }
        }
        
        dialog.setOnDismissListener {
            // 清理对话框引用
            when (dialogType) {
                "muted_list" -> currentMutedListDialog = null
                "kicked_list" -> currentKickedListDialog = null
            }
        }

        dialog.show()
    }

    fun showAnnouncementBottomSheet(context: Context, onPublish: (String) -> Unit) {
        val dialog = com.google.android.material.bottomsheet.BottomSheetDialog(context)
        val view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_announcement, null)
        dialog.setContentView(view)
        val etContent = view.findViewById<EditText>(R.id.et_announcement_content)
        val tvCount = view.findViewById<TextView>(R.id.tv_announcement_count)
        val btnPublish = view.findViewById<TextView>(R.id.btn_announcement_publish)
        val ivClose = view.findViewById<ImageView>(R.id.iv_announcement_close)
        // 字数统计
        etContent.addTextChangedListener(object : android.text.TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                tvCount.text = "${s?.length ?: 0}/80"
            }

            override fun afterTextChanged(s: android.text.Editable?) {}
        })
        // 发布按钮
        btnPublish.setOnClickListener {
            val text = etContent.text.toString().trim()
            onPublish(text)
            dialog.dismiss()
        }
        // 关闭按钮
        ivClose.setOnClickListener { dialog.dismiss() }
        dialog.show()
    }




    /**
     * 显示本地播放弹窗
     *
     * @param context 上下文
     * @param localFiles 本地文件列表
     * @param onTabChangeListener 选项卡切换监听器
     * @param onFileActionListener 文件操作监听器
     * @param onPlayControlListener 播放控制监听器
     */
    fun showLocalPlayDialog(
        context: Context, interstitialVideoUrl: List<Item>?
    ): BottomSheetDialog {
        val dialog = BottomSheetDialog(context)
        val view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_local_play, null)
        dialog.setContentView(view)
        lastLocalPlayDialog = dialog

        // 设置弹窗属性
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)

        // 初始化控件
        val tabLocalPlay = view.findViewById<TextView>(R.id.tab_local_play)
        val tabStream = view.findViewById<TextView>(R.id.tab_stream)
        val ivClose = view.findViewById<ImageView>(R.id.iv_close_local_play)
        val rvLocalPlay = view.findViewById<RecyclerView>(R.id.rv_local_play_list)

        // 播放控制控件
        val ivPlayPause = view.findViewById<ImageView>(R.id.iv_play_pause)
        val tvCurrentTime = view.findViewById<TextView>(R.id.tv_current_time)
        val tvTotalTime = view.findViewById<TextView>(R.id.tv_total_time)
        val ivLoop = view.findViewById<ImageView>(R.id.iv_loop)
        val ivFolder = view.findViewById<ImageView>(R.id.iv_folder)
        val seekBar = view.findViewById<SeekBar>(R.id.seekbar_progress)

        // 设置文件列表
        rvLocalPlay.layoutManager = LinearLayoutManager(context)
        val stored = loadLocalVideos(context)
        val names = stored.map { it.first }
        val adapter =
            LocalPlayAdapter(names.toMutableList()) { name, action ->
                val uri = stored.firstOrNull { it.first == name }?.second
                when (action) {
                    "preview" -> {
                        if (uri != null) {
                            val parsed = Uri.parse(uri)
                            // 同时支持在 Fragment 场景直接播放
                            when (context) {
                                is ThreePaneLiveActivity -> context.playLocalVideo(parsed)
                                is androidx.fragment.app.FragmentActivity -> {
                                    val frag = context.supportFragmentManager.findFragmentById(R.id.container_live)
                                    if (frag is com.streamer.app.fragment.LiveVideoFragment) {
                                        frag.playLocalVideo(parsed)
                                    }
                                }
                                else -> {}
                            }
                        }
                    }

                    "delete" -> {
                        removeLocalVideo(context, name)
                        (rvLocalPlay.adapter as? LocalPlayAdapter)?.removeFileByName(
                            name
                        )
                        // 如果正在播放被删文件，恢复摄像头
                        when (context) {
                            is ThreePaneLiveActivity -> context.showCameraPreview()
                            is androidx.fragment.app.FragmentActivity -> {
                                val frag = context.supportFragmentManager.findFragmentById(R.id.container_live)
                                if (frag is com.streamer.app.fragment.LiveVideoFragment) {
                                    frag.showCameraPreview()
                                }
                            }
                        }
                    }

                    "select" -> {
                        (rvLocalPlay.adapter as? LocalPlayAdapter)?.setSelectedItem(
                            name
                        )
                    }
                }
            }

        val loadAdapter =
            NetWorkPlayAdapter(interstitialVideoUrl as MutableList<Item>) { name, action ->
                when (action) {
                    "preview" -> {
                        when (context) {
                            is ThreePaneLiveActivity -> context.playSteamVideo(name)
                            is androidx.fragment.app.FragmentActivity -> {
                                val frag = context.supportFragmentManager.findFragmentById(R.id.container_live)
                                if (frag is com.streamer.app.fragment.LiveVideoFragment) {
                                    frag.playSteamVideo(name)
                                }
                            }
                            else -> {}
                        }
                    }

                    "delete" -> {
                        when (context) {
                            is ThreePaneLiveActivity -> context.showCameraPreview()

                            is androidx.fragment.app.FragmentActivity -> {
                                val frag = context.supportFragmentManager.findFragmentById(R.id.container_live)
                                if (frag is com.streamer.app.fragment.LiveVideoFragment) {
                                    frag.showCameraPreview()
                                }
                            }
                        }


                    }

                    "select" -> {

                    }
                }
            }
        rvLocalPlay.adapter = adapter

        // 选项卡切换
        tabLocalPlay.setOnClickListener {
            selectTab(tabLocalPlay, tabStream)
            rvLocalPlay.adapter = adapter

        }

        tabStream.setOnClickListener {
            selectTab(tabStream, tabLocalPlay)
            rvLocalPlay.adapter = loadAdapter

        }

        // 播放控制监听器
        ivClose.setOnClickListener { 
            dialog.dismiss()
            // 恢复摄像头预览
            when (context) {
                is ThreePaneLiveActivity -> context.showCameraPreview()
                is androidx.fragment.app.FragmentActivity -> {
                    val frag = context.supportFragmentManager.findFragmentById(R.id.container_live)
                    if (frag is com.streamer.app.fragment.LiveVideoFragment) {
                        frag.showCameraPreview()
                    }
                }
            }
        }
        ivFolder.setOnClickListener {
            // 处理文件选择
            when (context) {
                is ThreePaneLiveActivity -> {
                    // ThreePaneLiveActivity 的处理逻辑需要实现 pickLocalVideoAndRefresh 方法
                    context.pickLocalVideoAndRefresh(dialog)
                }
                is androidx.fragment.app.FragmentActivity -> {
                    val frag = context.supportFragmentManager.findFragmentById(R.id.container_live)
                    if (frag is com.streamer.app.fragment.LiveVideoFragment) {
                        frag.pickLocalVideoAndRefresh(dialog)
                    }
                }
            }
        }

        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
//                    onPlayControlListener("seek_$progress")
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        dialog.show()
        return dialog
    }

    fun refreshLocalPlayList() {
        val dialog = lastLocalPlayDialog ?: return
        val ctx = dialog.context ?: return
        val rv = dialog.findViewById<RecyclerView>(R.id.rv_local_play_list) ?: return
        val stored = loadLocalVideos(ctx)
        val names = stored.map { it.first }
        
        // 检查当前显示的是哪个tab
        val tabLocalPlay = dialog.findViewById<TextView>(R.id.tab_local_play)
        val tabStream = dialog.findViewById<TextView>(R.id.tab_stream)
        
        // 检查当前显示的是哪个tab（通过检查当前适配器类型）
        val currentAdapter = rv.adapter
        if (currentAdapter is com.streamer.app.adapter.LocalPlayAdapter) {
            // 如果当前显示的是本地播放tab，直接更新适配器
            currentAdapter.updateData(names)
        } else {
            // 如果当前显示的是流媒体tab，需要重新创建本地播放适配器并切换
            val adapter = com.streamer.app.adapter.LocalPlayAdapter(names.toMutableList()) { name, action ->
                val uri = stored.firstOrNull { it.first == name }?.second
                when (action) {
                    "preview" -> {
                        if (uri != null) {
                            val parsed = Uri.parse(uri)
                            when (ctx) {
                                is ThreePaneLiveActivity -> ctx.playLocalVideo(parsed)
                                is androidx.fragment.app.FragmentActivity -> {
                                    val frag = ctx.supportFragmentManager.findFragmentById(R.id.container_live)
                                    if (frag is com.streamer.app.fragment.LiveVideoFragment) {
                                        frag.playLocalVideo(parsed)
                                    }
                                }
                                else -> {}
                            }
                        }
                    }
                    "delete" -> {
                        removeLocalVideo(ctx, name)
                        (rv.adapter as? com.streamer.app.adapter.LocalPlayAdapter)?.removeFileByName(name)
                        when (ctx) {
                            is ThreePaneLiveActivity -> ctx.showCameraPreview()
                            is androidx.fragment.app.FragmentActivity -> {
                                val frag = ctx.supportFragmentManager.findFragmentById(R.id.container_live)
                                if (frag is com.streamer.app.fragment.LiveVideoFragment) {
                                    frag.showCameraPreview()
                                }
                            }
                        }
                    }
                    "select" -> {
                        (rv.adapter as? com.streamer.app.adapter.LocalPlayAdapter)?.setSelectedItem(name)
                    }
                }
            }
            rv.adapter = adapter
            // 切换到本地播放tab
            if (tabLocalPlay != null && tabStream != null) {
                selectTab(tabLocalPlay, tabStream)
            }
        }
    }

    fun getLastLocalPlayDialog(): BottomSheetDialog? = lastLocalPlayDialog

    // ================= Local storage helpers =================
    private const val PREFS = "local_play_prefs"
    private const val KEY_LIST = "local_videos"

    private fun loadLocalVideos(context: Context): MutableList<Pair<String, String>> {
        val sp = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
        val json = sp.getString(KEY_LIST, "[]") ?: "[]"
        val arr = JSONArray(json)
        val result = mutableListOf<Pair<String, String>>()
        for (i in 0 until arr.length()) {
            val obj = arr.getJSONObject(i)
            val name = obj.optString("name")
            val uri = obj.optString("uri")
            if (name.isNotEmpty() && uri.isNotEmpty()) result.add(name to uri)
        }
        return result
    }

    private fun saveLocalVideos(context: Context, list: List<Pair<String, String>>) {
        val arr = JSONArray()
        list.forEach { (name, uri) ->
            val obj = JSONObject()
            obj.put("name", name)
            obj.put("uri", uri)
            arr.put(obj)
        }
        context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
            .putString(KEY_LIST, arr.toString()).apply()
    }

    fun addLocalVideo(context: Context, name: String, uri: String) {
        val list = loadLocalVideos(context)
        if (list.none { it.second == uri }) {
            list.add(name to uri)
            saveLocalVideos(context, list)
        }
    }

    fun saveLocalVideo(context: Context, name: String, uri: String) {
        addLocalVideo(context, name, uri)
    }

    fun removeLocalVideo(context: Context, name: String) {
        val list = loadLocalVideos(context)
        val newList = list.filterNot { it.first == name }
        saveLocalVideos(context, newList)
    }

    /**
     * 选择选项卡
     */
    private fun selectTab(selectedTab: TextView, unselectedTab: TextView) {
        val context = selectedTab.context

        // 获取下划线指示器
        val selectedIndicator = (selectedTab.parent as? ViewGroup)?.findViewById<View>(
            if (selectedTab.id == R.id.tab_local_play) R.id.indicator_local_play else R.id.indicator_stream
        )
        val unselectedIndicator = (unselectedTab.parent as? ViewGroup)?.findViewById<View>(
            if (unselectedTab.id == R.id.tab_local_play) R.id.indicator_local_play else R.id.indicator_stream
        )

        // 选中状态
        selectedTab.setTextColor(context.getColor(R.color.blue_primary))
        selectedTab.setTypeface(null, android.graphics.Typeface.BOLD)
        selectedIndicator?.setBackgroundColor(context.getColor(R.color.blue_primary))

        // 未选中状态
        unselectedTab.setTextColor(context.getColor(R.color.gray))
        unselectedTab.setTypeface(null, android.graphics.Typeface.NORMAL)
        unselectedIndicator?.setBackgroundColor(context.getColor(android.R.color.transparent))
    }

    /**
     * 更新播放时间
     */
    fun updatePlayTime(dialog: BottomSheetDialog, currentTime: String, totalTime: String) {
        val view = dialog.findViewById<View>(android.R.id.content)
        view?.findViewById<TextView>(R.id.tv_current_time)?.text = currentTime
        view?.findViewById<TextView>(R.id.tv_total_time)?.text = totalTime
    }

    /**
     * 更新播放进度
     */
    fun updatePlayProgress(dialog: BottomSheetDialog, progress: Int) {
        val view = dialog.findViewById<View>(android.R.id.content)
        view?.findViewById<SeekBar>(R.id.seekbar_progress)?.progress = progress
    }

    /**
     * 更新播放状态图标
     */
    fun updatePlayIcon(dialog: BottomSheetDialog, isPlaying: Boolean) {
        val view = dialog.findViewById<View>(android.R.id.content)
        val playButton = view?.findViewById<ImageView>(R.id.iv_play_pause)
//        playButton?.setImageResource(
//            if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play_arrow
//        )
    }

    /**
     * 检查文件大小是否超过限制
     * @param context 上下文
     * @param uri 文件URI
     * @param maxSizeMB 最大文件大小（MB）
     * @return true 如果文件大小在限制内，false 如果超过限制
     */
    fun checkFileSize(context: Context, uri: android.net.Uri, maxSizeMB: Int = 200): Boolean {
        return try {
            val contentResolver: ContentResolver = context.contentResolver
            val cursor: Cursor? = contentResolver.query(uri, null, null, null, null)

            cursor?.use {
                if (it.moveToFirst()) {
                    val sizeIndex = it.getColumnIndex(OpenableColumns.SIZE)
                    if (sizeIndex != -1) {
                        val size = it.getLong(sizeIndex)
                        val sizeMB = size / (1024 * 1024)

                        if (sizeMB > maxSizeMB) {
                            android.widget.Toast.makeText(
                                context, "文件大小超过${maxSizeMB}MB限制，当前文件大小：${
                                    String.format(
                                        "%.1f", sizeMB
                                    )
                                }MB", android.widget.Toast.LENGTH_LONG
                            ).show()
                            return false
                        }
                        return true
                    }
                }
            }
            true
        } catch (e: Exception) {
            e.printStackTrace()
            android.widget.Toast.makeText(
                context, "无法获取文件大小信息", android.widget.Toast.LENGTH_SHORT
            ).show()
            true
        }
    }

    /**
     * 获取文件扩展名
     * @param fileName 文件名
     * @return 文件扩展名（小写）
     */
    fun getFileExtension(fileName: String): String {
        return if (fileName.contains(".")) {
            fileName.substring(fileName.lastIndexOf(".") + 1).lowercase()
        } else {
            ""
        }
    }

    /**
     * 检查文件格式是否支持
     * @param fileName 文件名
     * @return true 如果格式支持，false 如果不支持
     */
    fun isSupportedFileFormat(fileName: String): Boolean {
        val supportedFormats = arrayOf("pdf", "doc", "docx", "ppt", "pptx", "jpg", "jpeg", "png")
        val extension = getFileExtension(fileName)
        return supportedFormats.contains(extension)
    }

    /**
     * 从URI获取文件名
     * @param context 上下文
     * @param uri 文件URI
     * @return 文件名，如果获取失败返回null
     */
    fun getFileName(context: Context, uri: android.net.Uri): String? {
        return try {
            val contentResolver: ContentResolver = context.contentResolver
            val cursor: Cursor? = contentResolver.query(uri, null, null, null, null)

            cursor?.use {
                if (it.moveToFirst()) {
                    val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                    if (nameIndex != -1) {
                        return it.getString(nameIndex)
                    }
                }
            }
            null
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
} 